package com.gpframework.module.controller.manufacture;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.manufacture.domain.GpDyeingFactory;
import com.gpframework.module.manufacture.domain.GpProductionDetails;
import com.gpframework.module.manufacture.domain.req.GpProductionDetailsAdd;
import com.gpframework.module.manufacture.domain.req.GpProductionDetailsReq;
import com.gpframework.module.manufacture.domain.req.GpProductionDetailsUpdate;
import com.gpframework.module.manufacture.domain.vo.GpProductionDetailsVo;
import com.gpframework.module.manufacture.service.IGpDyeingFactoryService;
import com.gpframework.module.manufacture.service.IGpProductionDetailsService;
import com.gpframework.module.manufacture.service.IGpProductionSchedulingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
/**
 * @ClassName GpProductionDetailsController
 * @Author gpframework
 * @Date 2023-12-11
 * @Version 1.0.0
 * @Description 做货明细Controller
 */
@Validated
@Api(tags = "做货明细")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/manufacture/productionDetails" )
public class GpProductionDetailsController extends BaseController {

    private final IGpProductionDetailsService iGpProductionDetailsService;
    private final IGpProductionSchedulingService iGpProductionSchedulingService;
    private final IGpDyeingFactoryService iGpDyeingFactoryService;

 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2023-12-11
  * @Param gpProductionDetails
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:list')")
    @GetMapping("/list")
    public TableDataInfo<GpProductionDetailsVo> list(GpProductionDetailsReq gpProductionDetailsReq)
    {
        startPage();
        QueryWrapper<GpProductionDetails> lqw = new QueryWrapper<GpProductionDetails>();
        gpProductionDetailsReq.generatorQuery(lqw,true);
        List<GpProductionDetailsVo> list = iGpProductionDetailsService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:add')" )
    @Log(title = "添加做货明细" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GpProductionDetailsAdd gpProductionDetailsAdd) {


        GpProductionDetails gpProductionDetails = Convert.convert(new TypeReference<GpProductionDetails>() {}, gpProductionDetailsAdd);
        GpDyeingFactory gpDyeingFactory = iGpDyeingFactoryService.getById(gpProductionDetailsAdd.getDyeingFactoryId());
        gpProductionDetails.setSn(this.getSn(gpDyeingFactory.getCode()));
        gpProductionDetails.setDyeingFactoryName(gpDyeingFactory.getName());
        //初始化库存剩余数量
        gpProductionDetails.setLeaveGreyNum(gpProductionDetailsAdd.getStockGreyNum());
        //新增基础表数据
        iGpProductionDetailsService.initNoSn(gpProductionDetails);
        iGpProductionDetailsService.save(gpProductionDetails);
        return AjaxResult.success(gpProductionDetails);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:edit')" )
    @Log(title = "修改做货明细" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody List<GpProductionDetailsUpdate> list) {
        return toAjax(iGpProductionDetailsService.edit(list) ? 1 : 0);
    }


    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:export')" )
    @Log(title = "导出做货明细" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GpProductionDetailsReq gpProductionDetailsReq) {
        QueryWrapper<GpProductionDetails> lqw = new QueryWrapper<GpProductionDetails>();
        gpProductionDetailsReq.generatorQuery(lqw,true);
        List<GpProductionDetailsVo> list = iGpProductionDetailsService.listVo(lqw);
        ExcelUtil<GpProductionDetailsVo> util = new ExcelUtil<GpProductionDetailsVo>(GpProductionDetailsVo. class);
        return util.exportExcel(list, "productionDetails" );
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GpProductionDetailsVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProductionDetailsService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:remove')" )
    @Log(title = "删除做货明细" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGpProductionDetailsService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * @Description 生成生产排单表
     * @Author gpframework
     * @Date 2023-12-12
     * @Param gpProductionScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("生成生产排单表")
    @PreAuthorize("@ss.hasPermi('manufacture:productionScheduling:add')" )
    @Log(title = "生成生产排单表" , businessType = BusinessType.INSERT)
    @PostMapping("/createProductionScheduling")
    public AjaxResult createProductionScheduling(@Valid @RequestBody GpProductionDetailsUpdate gpProductionDetailsUpdate) {
        if (gpProductionDetailsUpdate == null || gpProductionDetailsUpdate.getId() == null) {
            return AjaxResult.parameterError();
        }
        return toAjax(iGpProductionSchedulingService.createProductionScheduling(gpProductionDetailsUpdate, null) ? 1 : 0);
    }


    //@ApiOperation("生成生产排单表")
    //@PreAuthorize("@ss.hasPermi('manufacture:productionScheduling:add')" )
    //@Log(title = "生成生产排单表" , businessType = BusinessType.INSERT)
    //@PostMapping("/createProductionScheduling")
    //public AjaxResult createProductionScheduling(@Valid @RequestBody GpProductionDetailsUpdate gpProductionDetailsUpdate) {
    //    if (gpProductionDetailsUpdate == null || gpProductionDetailsUpdate.getId() == null) {
    //        return AjaxResult.parameterError();
    //    }
    //    return toAjax(iGpProductionSchedulingService.createProductionScheduling(gpProductionDetailsUpdate.getId(), null) ? 1 : 0);
    //}

    /**
     * @Description 复制
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpProductionDetails
     * @Return TableDataInfo
     */
    @ApiOperation("复制")
    @PreAuthorize("@ss.hasPermi('manufacture:productionDetails:add')" )
    @Log(title = "复制" , businessType = BusinessType.INSERT)
    @PostMapping("/copy")
    public AjaxResult copy(@Valid @RequestBody GpProductionDetailsUpdate gpProductionDetailsUpdate) {
        if (gpProductionDetailsUpdate == null && gpProductionDetailsUpdate.getId() == null || gpProductionDetailsUpdate.getCopyNum() == null) {
            return AjaxResult.parameterError();
        }
        if (gpProductionDetailsUpdate.getCopyNum() < 1) {
            return AjaxResult.error("复制条数不能小于1");
        }
        return toAjax(iGpProductionDetailsService.copy(gpProductionDetailsUpdate.getId(), gpProductionDetailsUpdate.getCopyNum()) ? 1 : 0);
    }


    /**
     * @Description 拆分订单
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("拆分做货明细订单")
    @PreAuthorize("@ss.hasPermi('process:splitOrders:add')" )
    @Log(title = "拆分做货明细订单" , businessType = BusinessType.INSERT)
    @PostMapping("/splitOrders")
    public AjaxResult splitOrders(@Valid @RequestBody GpProductionDetailsUpdate gpProductionDetailsUpdate) {
        if (gpProductionDetailsUpdate == null || gpProductionDetailsUpdate.getId() == null || gpProductionDetailsUpdate.getSplitNum() == null) {
            return AjaxResult.parameterError();
        }
        if (gpProductionDetailsUpdate.getSplitNum() < 1) {
            return AjaxResult.error("拆分的胚布库存剩余数量不能小于1");
        }
        return toAjax(iGpProductionDetailsService.splitOrders(gpProductionDetailsUpdate.getId(), gpProductionDetailsUpdate.getSplitNum()) ? 1 : 0);
    }



    /**
     * 获取做货明细订单号
     * @param code
     * @return
     */
    private String getSn(String code) {
        String sn = "";
        if (StringUtils.isNotBlank(code)) {
            sn += code + "-";
        }
        String yyMMdd = DateUtils.getDate("yyMMdd");
        sn += yyMMdd;
        GpProductionDetails productionDetails = iGpProductionDetailsService.getOne(new LambdaQueryWrapper<GpProductionDetails>()
                .eq(GpProductionDetails::getDelStatus, YesNoEnum.NO.getKey())
                .isNotNull(GpProductionDetails::getSn)
                .gt(GpProductionDetails::getCreateTime, DateUtils.getDate("yyyy-MM-dd 00:00:00"))
                .orderByDesc(GpProductionDetails::getCreateTime)
                .last("limit 1"));
        if (productionDetails == null) {
            sn += "-1";
        } else {
            String substring = productionDetails.getSn().substring(productionDetails.getSn().lastIndexOf("-") + 1);
            int index = Integer.parseInt(substring) + 1;
            sn += "-" + index;
        }
        return sn;
    }
}
